import {
  ExecutionContext,
  HttpException,
  SetMetadata,
  createParamDecorator,
} from '@nestjs/common';
import { Request } from 'express';

export const IS_PUBLIC_KEY = 'isPublic';
export const Public = () => SetMetadata(IS_PUBLIC_KEY, true);

export const UserInfo = createParamDecorator(
  (data: string, ctx: ExecutionContext) => {
    const request = ctx.switchToHttp().getRequest<Request>();

    if (!request['user']) {
      return null;
    }
    return data ? request['user'][data] : request['user'];
  },
);

export const TenantInfo = createParamDecorator((_, ctx: ExecutionContext) => {
  const request = ctx.switchToHttp().getRequest<Request>();

  if (!request.headers['x-tenant-id']) {
    throw new HttpException('抱歉，您当前还没有选择商户', 400);
  }
  return request.headers['x-tenant-id'];
});

export const RequireRoles = (...roles: string[]) =>
  SetMetadata('require-roles', roles);
